package cn.edu.fzu.delivery.service.impl;

import cn.edu.fzu.delivery.common.SignValidator;
import cn.edu.fzu.delivery.domain.entity.Courier;
import cn.edu.fzu.delivery.domain.entity.CourierDelivery;
import cn.edu.fzu.delivery.domain.entity.SysUser;
import cn.edu.fzu.delivery.domain.enums.CourierStatusEnum;
import cn.edu.fzu.delivery.domain.enums.DeliveryStatusEnum;
import cn.edu.fzu.delivery.domain.enums.UserTypeEnum;
import cn.edu.fzu.delivery.helper.EmailHelper;
import cn.edu.fzu.delivery.helper.ShutDownHelper;
import cn.edu.fzu.delivery.io.DingDingMessage;
import cn.edu.fzu.delivery.io.OgReq;
import cn.edu.fzu.delivery.service.*;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.regex.Pattern;

/**
 * 钉钉机器人对接业务
 * 
 * @author fangxin
 * @date 2022/11/16
 */
@Service("dingDingService")
public class DingDingServiceImpl implements DingDingService {

    private static final Logger          log           = LoggerFactory.getLogger(DingDingServiceImpl.class);

    //邮箱正则校验
    private static final String          EMAIL_REGEX   = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
    private static final String          TITLE         = "快递平台";
    private static final DingDingMessage USAGE         = DingDingMessage.build(TITLE, "帮助说明", null,
            "courierId=快递单号: 快递信息", "delivery: 查询自己所有待派送快递件数", "info=快递单号+空格+消息:通知收件人信息", "deliveryAll:网点管理员一键派发所有快件");

    private final SignValidator          signValidator = SignValidator.deliveryInfo();

    @Resource
    private CourierService               courierService;
    @Resource
    private CourierDeliveryService       courierDeliveryService;
    @Resource
    private UserService                  userService;
    @Resource
    private NetworkAdminService          networkAdminService;
    @Resource
    private EmailHelper                  emailHelper;
    @Resource
    private ExecutorService              threadPool;

    @Override
    public DingDingMessage query(OgReq req, String timestamp, String sign) {

        if (!signValidator.validate(timestamp, sign)) {
            log.warn("sign not match, req={}, timestamp={}, sign={}", JSON.toJSONString(req), timestamp, sign);
            return null;
        }

        String command = req.getText().getContent().trim();

        if (Pattern.compile(EMAIL_REGEX).matcher(command).matches()) {
            SysUser user = userService.getSysUserByEmail(command);
            if (user == null) {
                return DingDingMessage.build(TITLE, "快递系统中不存在该邮箱用户", null);
            } else if (user.getDingId() != null) {
                return DingDingMessage.build(TITLE, "请不要绑定他人邮箱", null);
            } else {
                userService.updateSysUserDingId(command, req.getSenderId());
                return DingDingMessage.build(TITLE, "身份绑定成功", null);
            }
        }

        SysUser user = userService.getSysUserByDingId(req.getSenderId());
        if (user == null) {
            return DingDingMessage.build(TITLE, "请告诉我你是谁吧？@我 加上你的邮箱,只有邮箱正确才会绑定成功哦！", null);
        }

        if (command.startsWith("courierId=")) {
            return getCourier(user, command.substring(10));
        }

        if (Objects.equals(command, "delivery")) {
            return getDelivery(user);
        }
        if (command.startsWith("info=")) {
            return infoCustomer(user, command.substring(5));
        }
        if (Objects.equals(command, "deploy")) {
            return deploy(user);
        }
        if (Objects.equals(command, "deliveryAll")) {
            return deliveryAll(user);
        }
        return USAGE;
    }


    private DingDingMessage getCourier(SysUser user, String courierId) {
        Courier courier = courierService.getByCourierId(courierId);
        if (courier == null) {
            return DingDingMessage.build(TITLE, "快递不存在", Collections.singletonList(user.getPhone()));
        }
        return DingDingMessage.build(TITLE, "快递信息", Collections.singletonList(user.getPhone()),
                JSON.toJSONString(courier));
    }


    private DingDingMessage getDelivery(SysUser user) {

        if (user.getType() != UserTypeEnum.EXPRESS) {
            return DingDingMessage.build(TITLE, "您不是快递员", Collections.singletonList(user.getPhone()));
        }

        //派送中的快件
        List<CourierDelivery> deliveryList = courierDeliveryService.list(user.getId(), null,
                DeliveryStatusEnum.DELIVERING, null, null, null);
        //待取件的快件
        List<CourierDelivery> waitList = courierDeliveryService.list(user.getId(), null, DeliveryStatusEnum.WAIT, null,
                null, null);

        String[] items = new String[2];
        items[0] = "派送中的快递件数：" + deliveryList.size();
        items[1] = "待取件的快递件数：" + waitList.size();
        return DingDingMessage.build(TITLE, "快递情况", Collections.singletonList(user.getPhone()), items);
    }


    private DingDingMessage infoCustomer(SysUser user, String info) {
        String[] infos = info.split(" ");
        if (infos.length != 2) {
            return DingDingMessage.build(TITLE, "请填写正确的通知消息，请按正确格式填写", Collections.singletonList(user.getPhone()));
        }
        String courierId = infos[0];
        String content = infos[1];
        Courier courier = courierService.getByCourierId(courierId);
        if (courier == null) {
            return DingDingMessage.build(TITLE, "快递不存在", Collections.singletonList(user.getPhone()));
        }
        if (courier.getStatus() == CourierStatusEnum.ARRIVED) {
            return DingDingMessage.build(TITLE, "快递已签收，禁止骚扰顾客", Collections.singletonList(user.getPhone()));
        }
        if (emailHelper.sendMail(courier.getReceiver().getEmail(), "快递员通知", content)) {
            return DingDingMessage.build(TITLE, "已发送至收件人邮箱", Collections.singletonList(user.getPhone()));
        } else {
            return DingDingMessage.build(TITLE, "通知消息失败，邮件发送失败，收件人邮箱可能不正确", Collections.singletonList(user.getPhone()));
        }
    }


    /** 网点管理员一键派件快递 **/
    private DingDingMessage deliveryAll(SysUser user) {
        if (user.getType() != UserTypeEnum.NET_ADMIN) {
            return DingDingMessage.build(TITLE, "您不是网点管理员", Collections.singletonList(user.getPhone()));
        }
        List<Courier> courierList = networkAdminService.listDeliveryCouriers(user.getNetwork().getId(), null);
        if (CollectionUtils.isEmpty(courierList)) {
            return DingDingMessage.build(TITLE, "快递已经分发完毕", Collections.singletonList(user.getPhone()));
        }
        for (Courier courier : courierList) {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    networkAdminService.delivery(user, courier.getCourierId());
                }
            });
        }
        return DingDingMessage.build(TITLE, "快递已经分发完毕,请留意后续快递派发情况", Collections.singletonList(user.getPhone()),
                "派发快递件数：" + courierList.size());
    }


    /** 系统部署 **/
    private DingDingMessage deploy(SysUser user) {
        String deploy = ShutDownHelper.deploy();
        if (deploy != null) {
            return DingDingMessage.build(TITLE, "系统部署失败", Collections.singletonList(user.getPhone()), deploy);
        }
        return null;
    }
}
